<template>
  <div id="question-modal">
    <a-form
      ref="formRef"
      :rules="rules"
      :model="form"
      @submit-success="handleSubmit"
      :label-col-props="{ span: 3 }"
      :wrapper-col-props="{ span: 20 }"
    >
      <a-form-item field="title" label="标题：" validate-trigger="blur">
        <a-input v-model="form.title" placeholder="请输入标题" />
      </a-form-item>
      <a-form-item field="content" label="内容：">
        <a-textarea v-model="form.content" placeholder="请输入题目内容" />
      </a-form-item>
      <a-form-item field="bank" label="所属题库：" validate-trigger="blur">
        <a-select
          v-model="selectDefaultElem"
          placeholder="请选择所属题库"
          multiple
          @remove="handleRemove"
        >
          <a-option
            v-for="e in selectOptionElem"
            :key="e.id"
            :value="e.id"
            @click="handleInputChange(e.id)"
            >{{ e.title }}
          </a-option>
        </a-select>
      </a-form-item>
      <a-form-item field="tags" label="标签：">
        <a-input-tag
          v-model="form.tags"
          placeholder="题目标签，按Enter输入"
          allow-clear
        />
      </a-form-item>
      <a-form-item field="answer" label="答案：">
        <MyMDEditor ref="MDexpose"></MyMDEditor>
      </a-form-item>
      <a-form-item>
        <a-space>
          <a-button type="primary" html-type="submit" style="width: 150px"
            >{{ title }}
          </a-button>
        </a-space>
      </a-form-item>
    </a-form>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from "vue";
import {
  QuestionBankControllerService,
  QuestionBankQuestionControllerService,
  QuestionControllerService,
} from "../../../generated";
import notification from "@arco-design/web-vue/es/notification";
import MyMDEditor from "@/components/MyMDEditor.vue";
import message from "@arco-design/web-vue/es/message";

const props = defineProps(["closeModal", "title", "isUpdate", "list"]);
const selectDefaultElem = ref([]);
const selectOptionElem = ref([]);
const rules = {
  title: [{ required: true, message: "标题不能为空！" }],
  content: [{ required: true, message: "内容不能为空！" }],
};
const MDexpose = ref();

interface FormState {
  id?: string;
  title?: string;
  content?: string;
  tags?: Array<string>;
  answer?: string;
}

const form = reactive<FormState>({
  id: "",
  title: "",
  content: "",
  tags: [],
  answer: "",
});

const handleSubmit = (values: any) => {
  form.answer = MDexpose.value.content;
  if (props.isUpdate) {
    QuestionControllerService.updateQuestionUsingPost({ ...values }).then(
      (res) => {
        if (res.code === 0) {
          message.success("修改成功");
          // 刷新列表
          location.reload();
        } else {
          message.success("修改失败");
        }
      }
    );
  } else {
    QuestionControllerService.addQuestionUsingPost({ ...values }).then(
      (res) => {
        if (res.code === 0) {
          notification.success("新建题目成功");
          // 刷新列表
          location.reload();
        } else {
          notification.error("新建题目失败");
        }
      }
    );
  }
  // 关闭弹窗
  props.closeModal();
};

function handleEdit(value: any) {
  Object.assign(form, value);
  MDexpose.value.handleChange(value.answer);
  // 加载可选题库列表
  onloadSelectedBank();
  // 根据题目获取所属题库
  getQuestionBankByQuestionId(value["id"]);
}

function handleAdd(value: any) {
  Object.assign(form, value);
  MDexpose.value.handleChange(value.answer);
  // 加载可选题库列表
  onloadSelectedBank();
  // 清空默认题库
  selectDefaultElem.value.length = 0;
}

/**
 * 处理多选框的清除
 */
function handleRemove(questionBankId: string) {
  // console.log("删除题目id", form.id, "题库id", questionBankId);
  QuestionBankQuestionControllerService.deleteQuestionBankQuestionUsingPost({
    questionId: form.id,
    questionBankId: questionBankId,
  }).then((res) => {
    if (res.code === 0) {
      message.success("删除所属题库成功");
    } else {
      message.error("删除所属题库失败");
    }
  });
}

/**
 * 处理多选框输入
 */
function handleInputChange(questionBankId) {
  // console.log("加题目id", form.id, "题库id", questionBankId);
  QuestionBankQuestionControllerService.addQuestionBankQuestionUsingPost({
    questionId: form.id,
    questionBankId: questionBankId,
  }).then((res) => {
    if (res.code === 0) {
      message.success("增加所属题库成功");
    } else {
      message.error("增加所属题库失败");
    }
  });
}

defineExpose({ handleEdit, handleAdd });

/**
 * 加载可选题库列表
 */
function onloadSelectedBank() {
  QuestionBankControllerService.listQuestionBankByPageUsingPost({
    pageSize: 999,
  }).then((res) => {
    if (res.code === 0) {
      selectOptionElem.value = res.data.records;
    } else {
      message.error("题库获取异常");
    }
  });
}

/**
 * 加载所属题库列表
 */
function getQuestionBankByQuestionId(questionId: string) {
  QuestionBankQuestionControllerService.getQuestionBankByQuestionIdUsingPost(
    questionId
  ).then((res) => {
    console.log("获取到的题库", res);
    selectDefaultElem.value.length = 0;
    for (const e of res.data) {
      selectDefaultElem.value.push(e.id);
    }
  });
}
</script>
<style scoped></style>
